#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <error.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  int sockfd, n;
  struct sockaddr_in servaddr;

  if(argc != 2)
  {
    printf("usage: client <IPAddress>\n"); 
    exit(-1);
  }
  
  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    perror("fail to socket :");
    exit(-1);
  }

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(13);

  if(inet_aton(argv[1], &servaddr.sin_addr) == 0)
  {
    perror("fail to inet_aton: ");
    exit(-1);
  }

  if((connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0)
  {
    perror("fail to connect: ");
    exit(-1);
  }

  char buffer[4097];
  while((n = read(sockfd, buffer, 4096)) > 0)
  {
    buffer[n] = 0;
    if(fputs(buffer, stdout) == EOF)
    {
      perror("fail to fputs: ");
      exit(-1);
    }
  }
  if (n < 0)
  {
    perror("fail to read: ");
    exit(-1);
  }

  exit(0);
}
